<template>
  <div class="user-follow-list-container">
    <!-- 用户信息展示区域 -->
    <div class="user-profile">
      <div class="user-avatar">
        <img :src="targetUser.profilePicture || defaultAvatar" alt="avatar">
      </div>
      <div class="user-info">
        <h2>{{ targetUser.username }}</h2>
        <p class="user-bio">{{ targetUser.description || '这个人很懒，什么都没留下' }}</p>
        <div class="user-stats">
          <div class="stat-item">
            <span class="stat-value">{{ targetUser.articleCount }}</span>
            <span class="stat-label">文章</span>
          </div>
          <div class="stat-item">
            <span class="stat-value">{{ targetUser.likeCount }}</span>
            <span class="stat-label">获赞</span>
          </div>
          <div class="stat-item">
            <span class="stat-value">{{ targetUser.followerCount }}</span>
            <span class="stat-label">粉丝</span>
          </div>
          <div class="stat-item">
            <span class="stat-value">{{ targetUser.followingCount }}</span>
            <span class="stat-label">关注</span>
          </div>
        </div>
      </div>
      <!-- 根据条件判断是否显示关注按钮 -->
      <div v-if="profile.id!== targetUser.id" class="user-actions">
        <button
          :disabled="isProcessing[targetUser.id]"
          @click="handleTargetUserAction(targetUser.id)"
          :class="{ 'action-button': true, 'action-button--following': isFollowingMap[targetUser.id], 'action-button--not-following':!isFollowingMap[targetUser.id] }"
        >
          <span v-if="!isProcessing[targetUser.id]">
            {{ isFollowingMap[targetUser.id]? '取消关注' : '关注' }}
          </span>
          <span v-else>
            <i class="loading-icon fa fa-spinner fa-spin"></i> 处理中...
          </span>
        </button>
      </div>
    </div>
    
    <div class="tab-container">
      <div class="tab-buttons">
        <button
          :class="{ active: activeTab === 'following' }"
          @click="changeTab('following')"
        >
          关注列表
        </button>
        <button
          :class="{ active: activeTab === 'followers' }"
          @click="changeTab('followers')"
        >
          粉丝列表
        </button>
      </div>
      
      <div class="user-list">
        <div v-if="currentUserList.length === 0" class="empty-state">
          <div class="empty-icon">😢</div>
          <p>{{ activeTab === 'following' ? '暂无关注的用户' : '暂无粉丝' }}</p>
        </div>
        <div v-else v-for="user in currentUserList" :key="user.id" class="user-item">
          <div class="user-avatar">
            <img :src="user.profilePicture || defaultAvatar" alt="avatar">
          </div>
          <div class="user-info">
            <h3 class="clickable-username" @click="navigateToUserCenter(user.id)">{{ user.username }}</h3>
            <p class="user-bio">{{ user.description || '这个人很懒，什么都没留下' }}</p>
            <div class="user-stats">
              <div class="stat-badge">
                <span class="stat-icon">📝</span>
                <span>{{ user.articleCount }}</span>
              </div>
              <div class="stat-badge">
                <span class="stat-icon">👍</span>
                <span>{{ user.likeCount }}</span>
              </div>
              <div class="stat-badge">
                <span class="stat-icon">👥</span>
                <span>{{ user.followerCount }}</span>
              </div>
              <div class="stat-badge">
                <span class="stat-icon">🔔</span>
                <span>{{ user.followingCount }}</span>
              </div>
            </div>
          </div>
          <div class="user-actions">
            <button
              :disabled="isProcessing[user.id]"
              @click="handleAction(user.id)"
              :class="{ 'action-button': true, 'action-button--following': isFollowingMap[user.id], 'action-button--not-following':!isFollowingMap[user.id] }"
            >
              <span v-if="!isProcessing[user.id]">
                {{ isFollowingMap[user.id]? '取消关注' : '关注' }}
              </span>
              <span v-else>
                <i class="loading-icon fa fa-spinner fa-spin"></i> 处理中...
              </span>
            </button>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import { followUser, unfollowUser, getFollowingUsers, getFollowerUsers, isFollowing, findUserById } from '@/api/userApi.js';
import defaultAvatar from '@/imgs/avatar.png';
import { useUserStore } from '@/stores/userStore';
import { storeToRefs } from 'pinia';
import { useRoute, useRouter } from 'vue-router';

const route = useRoute();
const router = useRouter();
const targetUserId = ref(route.params.id);
const userStore = useUserStore();
const { profile } = storeToRefs(userStore);
// 根据路由参数初始化 activeTab
const activeTab = ref(route.params.tab || 'following');
const followingUsers = ref([]);
const followerUsers = ref([]);
const currentUserList = ref([]);
const isFollowingMap = ref({});
const isProcessing = ref({});
const targetUser = ref({});

const navigateToUserCenter = (userId) => {
  router.push(`/home/userCenter/${userId}`);
};

const fetchTargetUserInfo = async () => {
  try {
    const response = await findUserById(targetUserId.value);
    targetUser.value = response.data;
    // 获取目标用户的关注状态
    if (profile.id!== targetUser.value.id) {
      const res = await isFollowing(profile.value.id, targetUser.value.id);
      isFollowingMap.value[targetUser.value.id] = res.data;
      isProcessing.value[targetUser.value.id] = false;
    }
  } catch (error) {
    console.error('获取目标用户信息失败:', error);
  }
};

const fetchUserList = async (apiFunction, listRef) => {
  try {
    const response = await apiFunction(targetUserId.value, 1, 10);
    listRef.value = response.data;
    const followStatusPromises = listRef.value.map(async user => {
      const res = await isFollowing(profile.value.id, user.id);
      isFollowingMap.value[user.id] = res.data;
      isProcessing.value[user.id] = false;
    });
    await Promise.all(followStatusPromises);
    if (activeTab.value === (listRef === followingUsers? 'following' : 'followers')) {
      currentUserList.value = listRef.value;
    }
  } catch (error) {
    console.error('获取用户列表失败:', error);
  }
};

const fetchFollowingUsersList = () => fetchUserList(getFollowingUsers, followingUsers);
const fetchFollowerUsersList = () => fetchUserList(getFollowerUsers, followerUsers);

const handleTabChange = () => {
  if (activeTab.value === 'following') {
    currentUserList.value = followingUsers.value;
  } else {
    currentUserList.value = followerUsers.value;
  }
};

const changeTab = (tab) => {
  activeTab.value = tab;
  handleTabChange();
};

const handleAction = async (userId) => {
  isProcessing.value[userId] = true;
  try {
    if (isFollowingMap.value[userId]) {
      await unfollowUser({ followerId: profile.value.id, followingId: userId });
      isFollowingMap.value[userId] = false;
      console.log('取消关注成功');
    } else {
      await followUser({ followerId: profile.value.id, followingId: userId });
      isFollowingMap.value[userId] = true;
      console.log('关注成功');
    }
    if (activeTab.value === 'following') {
      await fetchFollowingUsersList();
    } else {
      await fetchFollowerUsersList();
    }
  } catch (error) {
    console.error('操作失败:', error);
  } finally {
    isProcessing.value[userId] = false;
  }
};

// 处理目标用户的关注操作
const handleTargetUserAction = async (userId) => {
  isProcessing.value[userId] = true;
  try {
    if (isFollowingMap.value[userId]) {
      await unfollowUser({ followerId: profile.value.id, followingId: userId });
      isFollowingMap.value[userId] = false;
      console.log('取消关注目标用户成功');
    } else {
      await followUser({ followerId: profile.value.id, followingId: userId });
      isFollowingMap.value[userId] = true;
      console.log('关注目标用户成功');
    }
    // 可以在这里添加更新目标用户粉丝数等逻辑
  } catch (error) {
    console.error('操作目标用户失败:', error);
  } finally {
    isProcessing.value[userId] = false;
  }
};

onMounted(async () => {
  await fetchTargetUserInfo();
  await fetchFollowingUsersList();
  await fetchFollowerUsersList();
  handleTabChange();
});
</script>

<style scoped>
.user-follow-list-container {
  padding: 30px;
  max-width: 900px;
  margin: 20px auto;
  background-color: #ffffff;
  border-radius: 16px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
}

/* 用户信息展示样式 */
.user-profile {
  display: flex;
  align-items: center;
  margin-bottom: 30px;
  padding: 25px;
  border-radius: 16px;
  background-color: #f8f9fa;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.05);
  transition: transform 0.3s ease;
}

.user-profile:hover {
  transform: translateY(-5px);
}

.user-profile .user-avatar {
  width: 120px;
  height: 120px;
  margin-right: 30px;
  border-radius: 50%;
  overflow: hidden;
  border: 4px solid #fff;
  box-shadow: 0 4px 10px rgba(0, 0, 0, 0.1);
}

.user-profile .user-avatar img {
  width: 100%;
  height: 100%;
  object-fit: cover;
  transition: transform 0.5s ease;
}

.user-profile .user-avatar img:hover {
  transform: scale(1.05);
}

.user-profile .user-info {
  flex: 1;
}

.user-profile .user-info h2 {
  font-size: 28px;
  font-weight: 700;
  margin-bottom: 8px;
  color: #333;
}

.user-bio {
  font-size: 16px;
  color: #666;
  margin-bottom: 15px;
  line-height: 1.5;
}

.user-stats {
  display: flex;
  gap: 20px;
  margin-top: 15px;
}

.stat-item {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.stat-value {
  font-size: 20px;
  font-weight: 700;
  color: #333;
}

.stat-label {
  font-size: 14px;
  color: #777;
  margin-top: 4px;
}

.tab-container {
  background-color: #fff;
  border-radius: 16px;
  overflow: hidden;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.05);
}

.tab-buttons {
  display: flex;
  background-color: #f8f9fa;
  padding: 5px;
  border-radius: 12px;
  margin-bottom: 25px;
}

.tab-buttons button {
  flex: 1;
  padding: 14px 20px;
  border: none;
  background-color: transparent;
  cursor: pointer;
  transition: all 0.3s ease;
  font-size: 16px;
  font-weight: 600;
  color: #666;
  border-radius: 10px;
}

.tab-buttons button.active {
  background-color: #007bff;
  color: white;
  box-shadow: 0 4px 10px rgba(0, 123, 255, 0.3);
}

.tab-buttons button:hover:not(.active) {
  background-color: #e9ecef;
  color: #333;
}

.user-list {
  display: flex;
  flex-direction: column;
  gap: 20px;
  padding: 10px 5px;
}

.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 50px 0;
  color: #999;
}

.empty-icon {
  font-size: 48px;
  margin-bottom: 15px;
}

.user-item {
  display: flex;
  align-items: center;
  padding: 20px;
  border-radius: 12px;
  background-color: #f8f9fa;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
  transition: all 0.3s ease;
}

.user-item:hover {
  transform: translateY(-3px);
  box-shadow: 0 6px 15px rgba(0, 0, 0, 0.1);
}

.user-avatar {
  width: 80px;
  height: 80px;
  margin-right: 20px;
  border-radius: 50%;
  overflow: hidden;
  border: 3px solid #fff;
  box-shadow: 0 3px 8px rgba(0, 0, 0, 0.1);
}

.user-avatar img {
  width: 100%;
  height: 100%;
  object-fit: cover;
  transition: transform 0.3s ease;
}

.user-avatar img:hover {
  transform: scale(1.05);
}

.user-info {
  flex: 1;
}

.user-info h3 {
  font-size: 20px;
  font-weight: 600;
  margin-bottom: 6px;
  color: #333;
}

.clickable-username {
  cursor: pointer;
  transition: color 0.3s ease;
}

.clickable-username:hover {
  color: #007bff;
  text-decoration: underline;
}

.user-stats {
  display: flex;
  gap: 12px;
  margin-top: 10px;
}

.stat-badge {
  display: flex;
  align-items: center;
  background-color: #e9ecef;
  padding: 5px 10px;
  border-radius: 20px;
  font-size: 14px;
  color: #555;
}

.stat-icon {
  margin-right: 5px;
}

.user-actions {
  margin-left: 20px;
}

.action-button {
  padding: 10px 20px;
  border: none;
  border-radius: 30px;
  cursor: pointer;
  transition: all 0.3s ease;
  font-weight: 600;
  font-size: 14px;
  box-shadow: 0 3px 8px rgba(0, 0, 0, 0.1);
}

.action-button--following {
  background-color: #f0f0f0;
  color: #666;
}

.action-button--following:hover {
  background-color: #ff4757;
  color: white;
}

.action-button--not-following {
  background-color: #007bff;
  color: white;
}

.action-button--not-following:hover {
  background-color: #0056b3;
  transform: translateY(-2px);
  box-shadow: 0 5px 15px rgba(0, 123, 255, 0.3);
}

.action-button:disabled {
  background-color: #e0e0e0;
  color: #999;
  cursor: not-allowed;
  box-shadow: none;
}

.loading-icon {
  margin-right: 5px;
  animation: spin 1s linear infinite;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

@media (max-width: 768px) {
  .user-follow-list-container {
    padding: 15px;
  }
  
  .user-profile {
    flex-direction: column;
    text-align: center;
  }
  
  .user-profile .user-avatar {
    margin-right: 0;
    margin-bottom: 20px;
  }
  
  .user-item {
    flex-direction: column;
    text-align: center;
  }
  
  .user-item .user-avatar {
    margin-right: 0;
    margin-bottom: 15px;
  }
  
  .user-actions {
    margin-left: 0;
    margin-top: 15px;
  }
}
</style>    